<template>
  <el-card>
    <!--  新增/修改弹出框  -->
    <el-dialog
        :title="dialogTitle+'权限'"
        :visible.sync="dialogAddOrUpdate"
        width="40%"
        :before-close="handleCloseAdd">
      <el-form :model="permissionFrom" :rules="permissionFromRules" ref="permissionFrom" label-width="100px">

        <el-form-item label="上级模块" prop="parentId">
          <el-select v-model="permissionFrom.parentId" placeholder="请选择上级模块" filterable style="width: 300px">
            <template v-for="item in tableData">
              <el-option :key="'parent-'+item.id" :label="'😎😎😎'+item.name" :value="item.id"></el-option>
              <template v-for="child in item.children">
                <el-option :key="'child-'+child.id" :label="child.name" :value="child.id">
                  <span>{{ " - " + child.name }}</span>
                </el-option>
              </template>
            </template>
          </el-select>
        </el-form-item>

        <el-form-item label="权限名称" prop="name">
          <el-input v-model="permissionFrom.name"></el-input>
        </el-form-item>

        <el-form-item label="权限标识" prop="value">
          <el-input v-model="permissionFrom.value"></el-input>
        </el-form-item>

        <el-form-item label="请求方式" prop="requestMethod">
          <my-select v-model="permissionFrom.requestMethod"
                     placeholder="请选择请求方式"
                     :showList="condition.requestMethodList"
                     labelName='label'
                     valueName='value'/>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="permissionFrom.sort" :min="0" label="数字越大排序越靠前"></el-input-number>
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input v-model="permissionFrom.description"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitAddOrUpdateForm('permissionFrom')">立即{{ dialogTitle }}</el-button>
          <el-button @click="resetForm('permissionFrom')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--  表格操作  -->
    <div class="select-div">
      <el-form :inline="true" style="height: 40px">

        <el-form-item>
          <el-input
              clearable
              v-model="condition.name"
              prefix-icon="el-icon-search"
              size="small"
              placeholder="请输入权限名称关键字"
              style="width:200px"
              @keyup.enter.native="searchPermissions"
          />
        </el-form-item>

        <el-form-item>
          <el-input
              clearable
              v-model="condition.value"
              prefix-icon="el-icon-search"
              size="small"
              placeholder="请输入权限标识关键字"
              style="width:200px"
              @keyup.enter.native="searchPermissions"
          />
        </el-form-item>

        <el-form-item>
          <my-select v-model="condition.requestMethod"
                     placeholder="请选择请求方式"
                     :showList="condition.requestMethodList"
                     labelName='label'
                     valueName='value'/>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" size="small" icon="el-icon-search" style="margin-left:1rem"
                     @click="searchPermissions">
            搜索
          </el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" size="small" icon="el-icon-plus" @click="dialogAdd">新增</el-button>
        </el-form-item>


        <el-form-item>
          <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteCheck()"
                     :disabled="this.selection.length === 0">删除选中
          </el-button>
        </el-form-item>

      </el-form>
    </div>

    <!--  表格内容  -->
    <el-table :data="tableData"
              row-key="id"
              border
              :isTree="true"
              :header-cell-style="{'text-align':'center'}"
              :cell-style="tableCellStyle"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
              @selection-change="handleSelectionChange">

      <el-table-column type="selection" width="55"></el-table-column>

      <el-table-column prop="name" label="权限名称"></el-table-column>

      <el-table-column prop="value" label="权限标识"></el-table-column>

      <el-table-column prop="requestMethod" label="请求方式">
        <template slot-scope="scope" v-if="scope.row.requestMethod">
          <el-tag :type="tagType(scope.row.requestMethod)">
            {{ scope.row.requestMethod }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="description" label="描述"></el-table-column>

      <el-table-column prop="sort" label="排序"></el-table-column>

      <el-table-column label="操作" fixed="right">
        <template slot-scope="scope">
          <el-tooltip effect="dark" content="编辑" placement="top-start">
            <el-button circle icon="el-icon-edit" size="mini" @click="handleEdit(scope.row.id)"/>
          </el-tooltip>

          <el-tooltip effect="dark" content="删除" placement="top-start">
            <el-button circle icon="el-icon-delete" size="mini" placement="top-start" type="danger"
                       @click="deleteCheck(scope.row.id)"/>
          </el-tooltip>
        </template>
      </el-table-column>

    </el-table>

    <!--  分页  -->
    <pagination
        :total="total"
        :page_index="pageNum"
        @pageChange="pageChange"
    />

  </el-card>
</template>

<script>
import { permissionApi } from '@/api';

export default {
  data() {
    return {
      tableData: [],
      selection: [],
      permissionFrom: {},
      total: 0,
      pageNum: 1,
      pageSize: 10,
      dialogAddOrUpdate: false,
      dialogTitle: '',
      condition: {
        name: null,
        value: null,
        method: null,
        requestMethod: null,
        requestMethodList: [
          {
            value: "GET",
            label: "GET"
          },
          {
            value: "POST",
            label: "POST"
          },
          {
            value: "PUT",
            label: "PUT"
          },
          {
            value: "DELETE",
            label: "DELETE"
          }
        ],
      },
      permissionFromRules: {
        name: [
          {required: true, message: '请输入权限名称', trigger: 'blur'}
        ],
        value: [
          {required: true, message: '请输入权限标识', trigger: 'blur'}
        ],
        requestMethod: [
          {required: true, message: '请选中请求方式', trigger: 'blur'}
        ],
        sort: [
          {required: true, message: '请设置排序序号', trigger: 'blur'}
        ],
      },
    }
  },

  methods: {
    /**
     * 复选框事件
     * @param selection 选中数据数组
     */
    handleSelectionChange(selection) {
      this.selection = selection.map(item => item.id)
      this.selectedNum = selection.length
    },

    /**
     * 搜索框事件
     */
    searchPermissions() {
      this.pageNum = 1;
      this.loadPermissionList();
    },

    /**
     * 分页回调函数
     * @param val
     */
    pageChange(val) {
      this.pageNum = val.pageNum;
      this.pageSize = val.pageSize;
      this.loadPermissionList();
    },

    /**
     * 新增按钮事件
     */
    dialogAdd() {
      this.dialogTitle = "新增";
      this.dialogAddOrUpdate = true;
    },

    /**
     * 编辑按钮触发事件
     * @param id 数据id
     */
    handleEdit(id) {
      permissionApi.getPermissionInfo(id).then((response) => {
        if (response.data.code === 20000) {
          //将当前行角色信息数据回显到弹出表单中，并打开表单
          this.permissionFrom = response.data.data;
          this.dialogTitle = "修改";
          this.dialogAddOrUpdate = true;
        }
      })
    },

    /**
     * 当用户通过点击关闭图标或遮罩关闭 Dialog 时起效的事件
     */
    handleCloseAdd() {
      //关闭Dialog时清空表单
      this.resetForm();
      this.dialogAddOrUpdate = false;
    },

    // 重置弹出框表单内容
    resetForm(formName) {
      this.$refs.permissionFrom.resetFields();
      this.permissionFrom = {};
    },

    /**
     * 提交新增/修改表单
     * @param formName
     */
    submitAddOrUpdateForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let data = this.permissionFrom;
          const apiMethod = this.permissionFrom.id ? permissionApi.updatePermission : permissionApi.addPermission;
          apiMethod(data).then((response) => {
            if (response.data.code === 20000) {
              this.$message({
                showClose: true,
                message: '操作成功！',
                type: 'success',
                onClose: () => {
                  this.loadPermissionListTree();
                }
              });
            }
          })
          this.dialogAddOrUpdate = false;
          this.resetForm(formName);
        } else {
          alert('请完整填写表单!');
          return false;
        }
      })
    },

    /**
     * 查询权限列表
     */
    loadPermissionList() {
      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        name: this.condition.name,
        value: this.condition.value,
        requestMethod: this.condition.requestMethod
      };
      
      permissionApi.getPermissionList(params).then((response) => {
        if (response.data.code === 20000) {
          if (response.data.data != null) {
            this.tableData = response.data.data.pagingList;
            this.total = response.data.data.count;
            return;
          }
          this.tableData = null;
          this.total = null;
        }
      });
    },

    /**
     * 查询树形权限列表
     */
    loadPermissionListTree() {
      permissionApi.getPermissionListTree().then((response) => {
        if (response.data.code === 20000) {
          this.tableData = response.data.data;
        }
      });
    },

    /**
     * 删除数据
     * @param id 数据id
     */
    deleteCheck(id) {
      this.$confirm("删除后不可恢复", "提示", {
        type: "warning"
      }).then(() => {
        const ids = id == null ? this.selection : [id];
        permissionApi.deletePermissions(ids).then((response) => {
          if (response.data.code === 20000) {
            this.$message.success("删除成功！")
          }
          this.loadPermissionListTree();
        });
      })
    },

    // 改变单元格背景颜色
    tableCellStyle({row, column, rowIndex, columnIndex}) {
      let rowBackground = {};
      if (row.parentId === null) {
        // rowBackground.background = '#f1ddc9'
      } else {
        rowBackground.background = '#d7c7dc'
      }
      return rowBackground
    },

  },

  computed: {
    tagType() {
      return function (type) {
        switch (type) {
          case "GET":
            return "";
          case "POST":
            return "success";
          case "PUT":
            return "warning";
          case "DELETE":
            return "danger";
        }
      };
    }
  },

  created() {
    // this.loadPermissionList();
    this.loadPermissionListTree();
  }
}
</script>

<style scoped>

</style>